package org.ajaxgroovyshell.servlet;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ajaxgroovyshell.ConsoleRunner;


public class GroovyReaderServlet extends HttpServlet {
	
	public static ConsoleRunner consoleRunner = new ConsoleRunner();
	static {
		consoleRunner.start();
		Thread.yield();
	}
	
	private static final long serialVersionUID = -582036403708248146L;

	@Override
	protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException,
			IOException {
		long start = System.currentTimeMillis();
		String input = ((String[])request.getParameterMap().get("keys"))[0];		
		char[] chars = new char[input.length()/2];		
		for(int i = 0; i < input.length()-1; i+=2) {
			chars[i/2] = (char)Integer.parseInt(input.substring(i, i+2), 16);
		}
		consoleRunner.pos.write(new String(chars).getBytes());
		sendReply("{'session': 'bsVGwKuustmNJKQK3HL2gA', 'sequence': 1}", response);
		long end = System.currentTimeMillis();
		System.out.println("Completed method in GroovyReaderServlet in " + (end - start));
	}
	
	@Override
	protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException,
			IOException {
		doPost(request, response);		
	}
	
	/**
	 * Write the response message to the output stream of the response. If the 
	 * responseEnvelope is null. The output stream will just be closed.
	 * 
	 * @param responseEnvelope
	 * @param response
	 * @throws IOException
	 */
	private void sendReply(String resp, final HttpServletResponse response) throws IOException{
		response.setContentType("Content-Type: application/json;charset=utf-8");
		final OutputStream outputStream = response.getOutputStream();
		try {			
			outputStream.write(resp.getBytes());
		} finally {
			outputStream.flush();
			outputStream.close();			
		}
	}
}
